<?php

namespace app\erp\controller;

use app\erp\model\Cartdb;
use app\erp\model\Goodsdb;
use app\erp\model\Orderdb;
use app\erp\model\SalePricedb;
use app\erp\model\Shoppingdb;
use PHPMailer\PHPMailer\PHPMailer;
use think\Controller;
use app\erp\model\Memberdb;
use app\erp\model\AccessConfigdb;
use app\erp\model\StaffAccessdb;
use app\erp\model\Systemdb;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use think\facade\Cache;

class Base extends Controller
{
    public function _initialize()
    {
        if (!session('member_id')) {
            $this->redirect('Login/index');
        }
        if (!defined('MEMBER_ID')) {
            define('MEMBER_ID', session('member_id'));
        }

        $member = new Memberdb ();
        $get_member = $member->memberInfo(MEMBER_ID);
        if (!defined('SITE_ID')) {
            define('SITE_ID', 117);
        }
        if (!defined('PARTNER_ID')) {
            define('PARTNER_ID', 25);
        }
        $this->assign('member_info', $get_member);
        if ($get_member ['member_id'] != 1) {
            $this->access($get_member ['member_id']);
        }
    }

    public function __system()
    {
        $controller = init_file('controller');
        $model = init_file('model');
        $validate = init_file('validate');
        $str = $controller . $model . $validate;
        $systemdb = new Systemdb ();
        $systemdb->param ['system_json'] = $str;
        return $systemdb->getSys();
    }

    protected function access($staff_id)
    {
        // 验证权限
        $request = request();
        $controller = $request->controller();
        $action = $request->action();
        $is_ajax = $request->isAjax();
        // 获取需要验证的权限
        $accessConfigdb = new AccessConfigdb ();
        $accessConfigdb->param ['page'] = 1;
        $accessConfigdb->param ['limit'] = 200;
        $get_need_access = $accessConfigdb->ajaxList();
        $need_flag = 0;
        $access_name = '';
        foreach ($get_need_access as $key => $val) {
            if ($val ['controller_name'] == $controller && strtolower($val ['function_name']) == $action) {
                $need_flag = 1;
                $access_name = $val ['use_intro'];
                break;
            }
        }
        if (in_array($action, ['shareGoods', 'shareContact'])) {
            $need_flag = 0;
        }
        if ($need_flag == 1) {
            // 获取当前用户拥有的权限
            $staffAccessdb = new StaffAccessdb ();
            $staffAccessdb->param ['staff_id'] = $staff_id;
            $get_staff_access = $staffAccessdb->getAccessOption();
            $get_option = $get_staff_access;
            $uri = url($controller . '/' . $action);
            if (!in_array($uri, $get_option)) {
                if ($is_ajax) {
                    $this->layuiReturn('您没有' . $access_name . '权限！', 0, '您没有' . $access_name . '权限！', -200);
                } else {
                    echo "<script>document.write('您没有" . $access_name . "权限！');</script>";
                    exit ();
                }
            }
        }
    }

    protected function ajaxReturn($data, $json_option = 0)
    {
        header('Content-Type:application/json; charset=utf-8');
        exit (json_encode($data, $json_option));
    }

    protected function layuiReturn($data, $count = 0, $msg = '', $code = 0)
    {
        $return ['data'] = $data;
        $return ['count'] = $count;
        $return ['msg'] = $msg;
        $return ['code'] = $code;
        $this->ajaxReturn($return);
    }

    public function getSheetValue($sheet, $index)
    {
        $value = $sheet->getCell($index)->getValue();
        if (is_object($value)) {
            $value = $value->__toString();
        }
        return $value;
    }
    // 发送短信
    /*
     * 新订单通知：SMS_225925355 {新订单提醒}-您好，军网平台有新的订单，单号：${order}，金额：${money}。地址：${address}。请及时处理。
     * 到账通知：SMS_225910508 {客户款到账提醒}-尊敬的合作伙伴您好，军网平台订单，单号：${order}，金额：${money}。客户款已到账，请及时查看，如有疑问可点击系统质疑按钮。
     * 付款通知：SMS_225935234 {货款支付提醒}-尊敬的合作伙伴您好，军网平台订单，单号：${order}，金额：${money}。货款已支付，请及时查看，如有疑问可点击系统质疑按钮。
     */
    public function sendMsg($phone, $tpl_code, $param)
    {
        $post_json = json_encode($param);
        $client = self::createClient();
        $sendSmsRequest = new SendSmsRequest ([
            "signName" => "泰龙吉",
            "phoneNumbers" => $phone,
            "templateCode" => $tpl_code,
            "templateParam" => $post_json
        ]);
        $result = $client->sendSms($sendSmsRequest);
        return $result;
    }

    public static function createClient()
    {
        $accessKeyId = 'LTAIeRWUxR6rp7sj';
        $accessKeySecret = 'n4qEWLCengJ012UAWl7UJvMOVMLgXY';
        $config = new Config ([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi ($config);
    }
    
    public function sendMail()
    {
        $request = request();
        $param = $request->param();
        // 同步邮件地址
        $orderdb = new Orderdb();
        $get_order = $orderdb->where('order_no', $param['order_no'])->find();
        if ($get_order) {
            $temp = json_decode($get_order['api_param'], true);
            $temp ['email'] = $param['to_mail'];
            $orderdb->where('order_id', $get_order['order_id'])->update(array('api_param' => json_encode($temp)));
        }

        $to = $param['to_mail'];
        $url = $request->server('DOCUMENT_ROOT') . str_replace('http://tailongji.dixintong.com', '', $param['file_url']);
        $url = str_replace('https://tailongji.dixintong.com', '', $url);
        $mail = new PHPMailer();
        $mail->isSMTP();
        $mail->CharSet = 'utf8';
        $mail->Host = 'smtp.263.net';
        $mail->SMTPAuth = true;
        $mail->Username = 'limengqi@dixintong.com';
        $mail->Password = 'f9fB3fEAE6B4B6C9';
        $mail->SMTPSecure = 'ssl';
        $mail->Port = 465;
        $mail->setFrom('limengqi@dixintong.com', '泰龙吉');  //定义邮件及标题
        $mail->addAddress($to);  //要发送的地址和设置地址的昵称
        $mail->addReplyTo('limengqi@dixintong.com', '泰龙吉');
        $mail->addAttachment($url);
        $mail->Subject = $param['order_no'] . "--泰龙吉";  //添加该邮件的主题
        $mail->Body = '详见附件'; //该邮件内容
        return $mail->send();
        return true;
    }

    public function shareGoods($order_no)
    {
        $orderdb = new Orderdb();
        $get_order_no = $orderdb->where('order_no', $order_no)->find();
        if (!$get_order_no) {
            halt('错误');
        }
        $cartdb = new Cartdb();
        $get_goods = $cartdb->with(['goods'])->where('site_id', 117)->where('order_no', $order_no)->select();
        $this->assign('goods', $get_goods);

        $this->assign('out_order_no', $get_order_no['out_order_no']);
        return $this->fetch();
    }

    public function shareContact($order_no)
    {
        $orderdb = new Orderdb();
        $get_order_no = $orderdb->where('order_no', $order_no)->find();
        if (!$get_order_no) {
            halt('错误');
        }
        $shoppingdb = new Shoppingdb();
        $get_order_no = $get_order_no->toArray();
        if ($get_order_no ['shopping_id']) {
            $shoppingdb->param ['shopping_id'] = $get_order_no ['shopping_id'];
            $get_shopping_info = $shoppingdb->ajaxFind($get_order_no ['shopping_id']);
            $get_order_no ['contacts'] = $get_shopping_info ['contacts'];
            $get_order_no ['contacts_phone'] = $get_shopping_info ['phone'];
        }
        $this->assign('order_info', $get_order_no);
        return $this->fetch();
    }

    /**
     * Title("发送邮件附件")
     */
    public function sendMailTpl($email, $url, $title,$attr_name)
    {
        $mail = new PHPMailer();
        $mail->isSMTP();
        $mail->CharSet = 'utf8';
        $mail->Host = 'smtp.263.net';
        $mail->SMTPAuth = true;
        $mail->Username = 'limengqi@dixintong.com';
        $mail->Password = 'f9fB3fEAE6B4B6C9';
        $mail->SMTPSecure = 'ssl';
        $mail->Port = 465;
        $mail->isHTML(true);
        $mail->setFrom('limengqi@dixintong.com', '泰龙吉');  //定义邮件及标题
        $mail->addAddress($email);  //要发送的地址和设置地址的昵称
        $mail->addReplyTo('limengqi@dixintong.com', '泰龙吉');
        $mail->Subject = $title;  //添加该邮件的主题
        $mail->Body = '详见附件'; //该邮件内容
        $mail->addAttachment($url,$attr_name);
        return $mail->send();
    }
}